package com.seeyon.apps.kkARPEvent.util;
import com.seeyon.ctp.cluster.ClusterConfigBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.file.model.CtpLocalFile;
import com.seeyon.ctp.common.htmltopdf.manager.HtmlToPdfManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.screenshot.manager.ScreenShotManager;
import com.seeyon.ctp.common.web.util.WebUtil;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.HttpClientUtil;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.v3x.common.security.AccessControlBean;
import com.seeyon.v3x.edoc.domain.EdocSummary;

import www.seeyon.com.utils.UUIDUtil;

import org.apache.commons.logging.Log;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Shu.Yang
 * @date 2022/4/18 - 15:22
 */
public class DocArchiveUtils {
    private static Log log = CtpLogFactory.getLog(DocArchiveUtils.class);
	private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");

    /**
     * rest账户   rest密码
     */
    public static final String REST_USER = AppContext.getSystemProperty("rcbtarget.restUserName");
    public static final String REST_PASSWORD = AppContext.getSystemProperty("rcbtarget.restUserPwd");
    
    public static String getContentUrl(String id, String type, ApplicationCategoryEnum category) throws BusinessException {
        String url = null;
        switch (category) {
            case edoc:
                /* url = "/govdoc/govdoc.do?method=summary&summaryId="+summary.getId();*/
                url = "/govdoc/govdoc.do?method=showPrintForm&openFrom=listDone&affairId="+id+"&isShowComment=false&isReplyContent=false&isShowContent=true";
                break;
            case collaboration:
                url = "/collaboration/collaboration.do?method=showPrintForm&openFrom=listDone&affairId="+id+"&isShowComment=true&isReplyContent=true";
                break;
            case doc:
                url = "/doc.do?method=docOpenBody&docResId=" + id + "&docLibType=" + type;
                break;
        }
        return url;
    }

    public static boolean htmlToPdf(String url, String pdfPath, ApplicationCategoryEnum category, String subjectID) throws BusinessException {
        if (Strings.isBlank(url) || Strings.isBlank(pdfPath)) return false;
        if(category==ApplicationCategoryEnum.collaboration||category==ApplicationCategoryEnum.edoc||category==ApplicationCategoryEnum.form){
            try {
                ScreenShotManager screenShotManager=(ScreenShotManager) AppContext.getBean("screenShotManager");
                ScreenShotManager.ScreenShotParam screenShotParam=new ScreenShotManager.ScreenShotParam();
                screenShotParam.setFilePath(pdfPath);
                screenShotManager.htmlToPdf(url,screenShotParam,category);
                return new CtpLocalFile(pdfPath).exists();
            } catch (Exception e) {
                throw new BusinessException("html转pdf出错:", e);
            }
        }else{
            HttpServletRequest request = WebUtil.getRequest();
            if (request != null) {
                String u = request.getRequestURL().toString();
                String requestURI = request.getRequestURI();
                String host = u.replace(requestURI,"");
                if (category != null && Strings.isNotBlank(subjectID)){
                    AccessControlBean.getInstance().addAccessControl(category, subjectID, AppContext.currentUserId());
                }
                url = host + "/seeyon"+url;
            }
            try {
                HtmlToPdfManager htmlToPdfManager = (HtmlToPdfManager) AppContext.getBean("htmltopdfManager");
                String filePath = htmlToPdfManager.singleHtmlToPdf(url, pdfPath, null);
                log.info(filePath);
                return new CtpLocalFile(pdfPath).exists();
            } catch (Exception e) {
                throw new BusinessException("html转pdf出错:", e);
            }
        }
    }
    
	public static boolean autoHtmlToPdf(String url, String pdfPath, ApplicationCategoryEnum category, String subjectID,
			Long startUserId) throws BusinessException {
		HttpClientUtil token_httpClient = new HttpClientUtil();
		HttpClientUtil httpClient = new HttpClientUtil();
		try {
			//1、获取token
			V3xOrgMember memberSender = orgManager.getMemberById(startUserId);
			ClusterConfigBean instance = ClusterConfigBean.getInstance();
			String oaUrl = "http://" + instance.getLocalhost() + ":7003" ;
			log.info("html自动转pdf获取oaUrl:" + oaUrl);
			String tokenUrl =  oaUrl + "/seeyon/rest/token/";
			Map<String, Object> token_param = new HashMap<String, Object>();
			token_param.put("userName", REST_USER);
			token_param.put("password", REST_PASSWORD);
			token_param.put("loginName", memberSender.getLoginName());
			
			token_httpClient.open(tokenUrl, "POST");
			token_httpClient.setRequestBodyJson(token_param);
			token_httpClient.send();
			Map tokenResult = token_httpClient.getResponseJsonAsObject(Map.class);
			log.info("html自动转pdf获取tokenResult:" + tokenResult);
			//2、调用截图rest接口
			String toPdfUrl = oaUrl + "/seeyon/rest/capFormTo/pdf";			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("url", url);
			param.put("pdfPath", pdfPath);
			param.put("category", category);
			param.put("subjectID", subjectID);
			
			httpClient.open(toPdfUrl, "POST");
			httpClient.setRequestBodyJson(param);
			httpClient.setRequestHeader("token", ParamUtil.getString(tokenResult, "id"));
			httpClient.setRequestHeader("Cookie", "JSESSIONID=" + UUIDUtil.getUUIDString());
			httpClient.send();
			boolean result = httpClient.getResponseJsonAsObject(Boolean.class);
			log.info("html自动转pdf结果result:" + result);
			return result;
		} catch (Exception e) {
			log.error("html自动转pdf出错:", e);
			throw new BusinessException("html自动转pdf出错:", e);
		} finally {
			if (token_httpClient != null) {
				token_httpClient.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
		}
	}
}
